package com.deng.mail.authserver.mailauthserver.service.impl;

import com.deng.mail.authserver.mailauthserver.service.SmsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    public static final String REDIS_SMS_PREFIX = "sms:";
    private Random random = new Random();

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean sendSms(String phone) {
        String existCode = redisTemplate.opsForValue().get(REDIS_SMS_PREFIX + phone);
        if (!StringUtils.isEmpty(existCode)) {
            long time = Long.parseLong(existCode.split("_")[1]);
            // 60秒内不能重复发送验证码
            if (System.currentTimeMillis() - time > 60000) {
                return false;
            }
        }

        String code = random.nextInt(1000_000) + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(REDIS_SMS_PREFIX + phone, code, 10, TimeUnit.MINUTES);
        // 调用第三方服务发送验证码 feign
        // thirdService.sendSms(phone, code.split("_")[0];
        return true;
    }
}
